package com.wfw.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wfw.model.LogInfo;
import com.wfw.model.ProductCategory;
import com.wfw.model.ProductInfo;
import com.wfw.service.ProductCategoryService;
import com.wfw.service.ProductInfoService;
import com.wfw.vo.ProductInfoVo;
import com.wfw.vo.ProductVo;
import com.wfw.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/buyer/product")
@Slf4j
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    public ResultVo list(){
        /*try {
            int i=1/0;
        }catch (Exception e){
            log.error(">>>>>>",e);
        }*/
        //1.查询所有的上架商品
        List<ProductInfo> productInfoList=productInfoService.findUpAll();

        //2.查询类目（一次性查询）
        //java8,lambda,拉姆达表达式
        List<Integer> categoryTypeList=
                productInfoList.stream().
                        map(productInfo -> productInfo.getCategoryType()).
                        collect(Collectors.toList());

        List<ProductCategory> productCategoryList=productCategoryService.findByCategoryTypeIn(categoryTypeList);

        //3.数据拼装
        List<ProductVo> productVoList=Lists.newArrayList();
        productCategoryList.forEach(item -> {
            ProductVo productVo=new ProductVo();
            productVo.setCategoryType(item.getCategoryType());
            productVo.setCategoryName(item.getCategoryName());

            List<ProductInfoVo> productInfoVoList=Lists.newArrayList();
            productInfoList.forEach(productInfo -> {
                if (productInfo.getCategoryType().equals(item.getCategoryType())){
                    ProductInfoVo productInfoVo=new ProductInfoVo().convertFor(productInfo);
                    productInfoVoList.add(productInfoVo);
                }
            });
            productVo.setProductInfoVoList(productInfoVoList);
            productVoList.add(productVo);
        });

        return ResultVo.createBySuccessData(productVoList);
    }

    @GetMapping
    public Map<String,Object> test(){
        Map<String,Object> map= Maps.newHashMap();
        LogInfo logInfo=new LogInfo();
        logInfo.setUrl("dkjfkdsjf");
        logInfo.setRequestIp("asadasa");
        map.put("type","tf02");
        map.put("uuid","sdjakdjkasj");
        map.put("data",logInfo);
        return map;
    }
}
